#include <linux/module.h>
#include <linux/poll.h>

#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/kmod.h>
#include <linux/gfp.h>
#include <linux/gpio/consumer.h>
#include <linux/platform_device.h>
#include <linux/of_gpio.h>
#include <linux/of_irq.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <asm/current.h>
#include <linux/fs.h>
#include <linux/wait.h>
#include <linux/completion.h>

/**
* 就认为只有一个sr501的设备
*/

struct sr501_driver_info {
	const char *sr501_name;
	int sr501_major;
	struct class *sr501_class;
};

struct sr501_device_info {
	struct gpio_desc *gpiod;
	int gpio_no;
	int irq_no;
	int dev_no;
	enum of_gpio_flags flags;

	struct completion r_completion;
	spinlock_t spinlock;

	int has_data;
	int dev_data;
};

static struct sr501_driver_info driver_info = {
	.sr501_name = "sr501",
	.sr501_major = 0,
	.sr501_class = NULL,
};

static struct sr501_device_info device_info = {

};

static const struct of_device_id sr_ids[] = {
	{ .compatible = "100ask,sr501" },
	{},
};

static int sr501_probe(struct platform_device *pdev);
static int sr501_remove(struct platform_device *pdev);

static struct platform_driver sr_driver = {
	.probe		= sr501_probe,
	.remove 	= sr501_remove,
	.driver		= {
		.name	= "sr501",
		.of_match_table = sr_ids,
	},
};

irqreturn_t sr501_handler(int irq, void *dev_id)
{
	printk("func = %s, irq = %d. \n", __func__, irq);
	struct sr501_device_info *dev = (struct sr501_device_info *)dev_id;

	spin_lock(&dev->spinlock);
	dev->has_data = true;
	dev->dev_data = 1;
	spin_unlock(&dev->spinlock);

	// 这里不适用complete的原因是，会不断进行通知，可能造成done反转。
	// complete(&dev->r_completion);
	complete_all(&dev->r_completion);

	return IRQ_HANDLED;
}

static int sr501_probe(struct platform_device *pdev)
{
	printk("func = %s .\n", __func__);

	struct device_node *node = (struct device_node *)pdev->dev.of_node;

	int count = of_gpio_count(node);
	if (1 != count)
	{
		printk("func = %s, line = %d,gpio count is wrong.\n", __func__,
		       __LINE__);
		return -1;
	}

	device_info.gpio_no = of_get_gpio_flags(node, 0, &device_info.flags);

	if (device_info.gpio_no < 0)
	{
		printk("func = %s,line = %d,gpio no is %d .\n", __func__,
		       __LINE__, device_info.gpio_no);
		return -1;
	}
	device_info.gpiod = gpio_to_desc(device_info.gpio_no);
	device_info.flags = device_info.flags & OF_GPIO_ACTIVE_LOW;
	device_info.irq_no = gpiod_to_irq(device_info.gpiod);
	device_info.has_data = false;

	gpiod_direction_input(device_info.gpiod);

	spin_lock_init(&device_info.spinlock);

	init_waitqueue_head(&device_info.r_wait_queue);

	device_info.dev_no = 0;
	device_create(driver_info.sr501_class, NULL,
		      MKDEV(driver_info.sr501_major, device_info.dev_no), NULL,
		      "sr501");

	dev_set_drvdata(&pdev->dev, &device_info);

	request_irq(device_info.irq_no, sr501_handler,
		    IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "sr501",
		    &device_info);

	return 0;
}
static int sr501_remove(struct platform_device *pdev)
{
	struct sr501_device_info *dev = dev_get_drvdata(&pdev->dev);

	if (!dev)
	{
		return -1;
	}

	free_irq(device_info.irq_no, dev);

	device_destroy(driver_info.sr501_class,
		       MKDEV(driver_info.sr501_major, dev->dev_no));

	return 0;
}

int sr501_open(struct inode *node, struct file *filp)
{
	filp->private_data = &device_info;

	return 0;
}

ssize_t sr501_read(struct file *filp, char __user *buf, size_t size,
		   loff_t *pos)
{
	struct sr501_device_info *dev =
		(struct sr501_device_info *)filp->private_data;

	unsigned long flags;
	int ret = 0;

	// wait + reinit 实际上变成了两部分代码，
	// 比如reinit后，又有数据到来，但后续会将所有的数据读走；但completion标识还有数据，这肯定是有问题的。
	wait_for_completion(&dev->r_completion);
	reinit_completion(&dev->r_completion);

	spin_lock_irqsave(&dev->spinlock, flags);
	while (!dev->has_data)
	{
		// 没有数据
		spin_unlock_irqrestore(&dev->spinlock, flags);
		__set_current_state(TASK_INTERRUPTIBLE);
		schedule();

		// 唤醒后，设置进程状态
		__set_current_state(TASK_RUNNING);

		spin_lock_irqsave(&dev->spinlock, flags);
		if (signal_pending(current))
		{
			ret = -ERESTARTSYS;
			break;
		}
	}
	// 有数据
	if (ret == 0)
	{
		ret = size > sizeof(dev->dev_data) ? sizeof(dev->dev_data) :
						     size;
		copy_to_user(buf, &dev->dev_data, ret);
		dev->has_data = false;
	}

	spin_unlock_irqrestore(&dev->spinlock, flags);

	return ret;
}

__poll_t sr501_poll(struct file *filp, struct poll_table_struct *wait_table)
{
	__poll_t mask = 0;
	unsigned long flags = 0;
	struct sr501_device_info *dev =
		(struct sr501_device_info *)filp->private_data;

	poll_wait(filp, &dev->r_wait_queue, wait_table);

	spin_lock_irqsave(&dev->spinlock, flags);
	if (dev->has_data)
	{
		mask |= EPOLLIN | EPOLLRDNORM;
	}
	spin_unlock_irqrestore(&dev->spinlock, flags);

	return mask;
}

static const struct file_operations sr501_fops = {
	.owner = THIS_MODULE,
	.open = sr501_open,
	.read = sr501_read,
	.poll = sr501_poll,
};

static int __init sr_init(void)
{
	printk("func = %s .\n", __func__);
	driver_info.sr501_major =
		register_chrdev(0, driver_info.sr501_name, &sr501_fops);

	driver_info.sr501_class = class_create(THIS_MODULE, "sr501_class");

	platform_driver_register(&sr_driver);
	return 0;
}

static void __exit sr_exit(void)
{
	printk("func = %s .\n", __func__);

	unregister_chrdev(driver_info.sr501_major, driver_info.sr501_name);
	class_destroy(driver_info.sr501_class);
	platform_driver_unregister(&sr_driver);
}

module_init(sr_init);
module_exit(sr_exit);
MODULE_LICENSE("GPL");